from datetime import datetime
from io import BytesIO

import xlwt
from django.shortcuts import HttpResponse
from django.urls import re_path

from stark.service.v1 import StarkHandler, Option, get_m2m_text, get_datetime_text, get_choice_text
from web import models
from web.utils import ipv4_tools
from web.utils.queryset import get_subnet_queryset


class IpSubnetRecordQueryHandler(StarkHandler):
    list_display = [
        StarkHandler.display_checkbox,
        get_choice_text('操作类型', 'operate_type'),
        'ip_subnet',
        'service_type',
        get_m2m_text('使用单位', 'depart'),
        'location',
        'responsible_person',
        get_datetime_text('操作日期', 'operate_date')
    ]

    def get_urls(self):
        """
        二次路由分发
        :return:
        """
        patterns = [
            re_path(r'^list/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            # re_path(r'^add/(?P<subnet_id>\d+)/$', self.wrapper(self.add_view), name=self.get_add_url_name),
            # re_path(r'^change/(?P<pk>\d+)/$', self.wrapper(self.change_view),
            #         name=self.get_change_url_name),
            # re_path(r'^delete/(?P<pk>\d+)/$', self.wrapper(self.delete_view),
            #         name=self.get_delete_url_name)
        ]
        patterns.extend(self.extra_url())
        return patterns

    def get_list_display(self, request, *args, **kwargs):
        """
        预留列表页面显示字段的钩子函数
        :return:
        """
        value = []
        if self.list_display:
            value.extend(self.list_display)
        return value

    order_list = ['-operate_date', ]
    search_list = ['location__contains', 'responsible_person__contains', 'ip_subnet__subnet__contains']
    search_group = [Option('depart'), Option('service_type')]

    def get_add_btn(self, request, *args, **kwargs):
        return None

    def action_multi_export_excel(self, request, *args, **kwargs):
        now_time = datetime.now().strftime('%Y-%m-%d')
        pk_list = request.POST.getlist('pk')
        pk_list = set(pk_list)
        # 设置HTTPResponse的类型
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=%s.xls' % now_time
        # 创建一个文件对象
        wb = xlwt.Workbook(encoding='utf8')
        # 创建一个sheet对象
        sheet = wb.add_sheet('sheet1')

        # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改

        # 写入文件标题
        sheet.write(0, 0, '序号')
        sheet.write(0, 1, '网络地址')
        sheet.write(0, 2, '子网掩码')
        sheet.write(0, 3, '起始地址')
        sheet.write(0, 4, '结束地址')
        sheet.write(0, 5, '网关')
        sheet.write(0, 6, '使用单位')
        sheet.write(0, 7, '负责人')
        data_row = 1
        for pk in pk_list:
            subnet_object = models.IpSubnetRecord.objects.filter(id=pk).first()
            subnet = subnet_object.subnet
            network_address = ipv4_tools.get_network_address(subnet)
            net_mask = ipv4_tools.get_net_mask(subnet)
            start_address = ipv4_tools.get_start_addrss(subnet)
            end_address = ipv4_tools.get_end_address(subnet)
            default_gateway = ipv4_tools.get_gateway(subnet)
            depart = [item['title'] for item in subnet_object.depart.values('title')]
            responsible_person = subnet_object.responsible_person
            # 写入数据
            # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
            # for i in UserTable.objects.all():
            # 格式化datetime
            # pri_time = i.pri_date.strftime('%Y-%m-%d')
            # oper_time = i.operating_time.strftime('%Y-%m-%d')
            sheet.write(data_row, 0, data_row)
            sheet.write(data_row, 1, network_address)
            sheet.write(data_row, 2, net_mask)
            sheet.write(data_row, 3, start_address)
            sheet.write(data_row, 4, end_address)
            sheet.write(data_row, 5, default_gateway)
            sheet.write(data_row, 6, depart)
            sheet.write(data_row, 7, responsible_person)

            data_row = data_row + 1

            # 写出到IO
            output = BytesIO()
            wb.save(output)
            # 重新定位到开始
            output.seek(0)
            response.write(output.getvalue())
            return response

    action_multi_export_excel.text = '批量导出excel'

    action_list = [action_multi_export_excel, ]

    def get_queryset(self, request, *args, **kwargs):
        current_user_id = request.session['user_info']['user_id']
        user_object = models.UserInfo.objects.filter(id=current_user_id).first()
        queryset = self.model_class.objects.all()
        if not user_object.is_depart:
            return queryset
        subnet_queryset_list = get_subnet_queryset().filter(depart=user_object.depart)
        subnet_list = [item.id for item in subnet_queryset_list]
        queryset = queryset.filter(ip_subnet_id__in=subnet_list)
        return queryset
